package com.itheima.thread.communication.demo05;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

// 消费者线程的任务类
public class CustomerThread implements Runnable {

    private Box box ;
    private ReentrantLock reentrantLock ;
    private Condition condition ;
    public CustomerThread(Box box , ReentrantLock reentrantLock , Condition condition) {            // 定义接收奶箱的构造方法
        this.box = box ;
        this.reentrantLock = reentrantLock ;
        this.condition = condition ;
    }

    @Override
    public void run() {

        // 创建奶箱
        // Box box = new Box() ;

        // 消费者线程需要不断的消费奶
        while(true) {

            // 加锁
            reentrantLock.lock();

            // 判断奶箱中是否有奶，如果没有奶等待
            if(!box.isFlag()) {
                try {
                    condition.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

            // 对数据进行消费
            System.out.println(box.getMilkType() + "----" + box.getAmount());

            // 修改flag的为false
            box.setFlag(false);

            // 唤醒生产者线程，去生产奶
            condition.signal();

            // 释放锁
            reentrantLock.unlock();
        }

    }

}
